package com.scs.application.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.sys.entity.Printer;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.service.PrinterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @descript 打印机控制类
 */
@RestController
@RequestMapping("/sys/printer")
public class PrinterController extends CrudController<PrinterService, Printer> {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @PostMapping("/reportPrinter")
    RestResult reportPrinter(@RequestBody Printer printer) {
        //@RequestHeader("warehouseId") String warehouseId,
        String message = "";
        service.SavePrinter(printer);

        HashMap mapReturn = new HashMap();
        message = "服务端收到 url = " + printer.getUrl() + " 打印机名称：" + printer.getName();
        mapReturn.put("result", message);

        logger.info(message);
        return RestResult.ok(message, mapReturn);
    }

    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Printer printer) {
        if(StringUtils.isBlank(printer.getId()) && "rfidOut".equals(printer.getTypeKey())){
            Printer old = service.getOne(new QueryWrapper<Printer>().eq("type_key", "rfidOut"));
            if (old != null) return RestResult.error("RFID打印机（外部调用）配置已经存在,不允许配置多个，数据保存失败");
        }
        boolean isOk = service.saveOrUpdate(printer);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功", printer);
    }

    @PostMapping("/printLabel")
    public RestResult print(@RequestHeader("warehouseId") String warehouseId, @RequestBody Map map) {
        if (StringUtils.isBlank(warehouseId)) {
            return RestResult.error("请先配置工位！");
        }
        String labelKey = map.get("labelKey").toString();
        Object data = map.get("data");
        return service.printLabel(warehouseId, labelKey, data);
    }
}
